# -*- coding: utf-8 -*-
"""
Created on Wed Sep 17 14:11:32 2025

@author: surpass
"""

# 学生成绩管理系统 - 针对图片1的数据结构

students = []  # 主列表存储所有学生信息

def add_stu():
    """添加学生信息"""
    print("\n--- 添加学生信息 ---")
    while True:
        try:
            # 基本信息
            student_id = input("请输入学号: ").strip()
            name = input("请输入姓名: ").strip()
            class_name = input("请输入班级: ").strip()
            
            # 实验成绩 (8次)
            experiments = []
            print("请输入8次实验成绩:")
            for i in range(1, 9):
                score = float(input(f"实验{i}: "))
                experiments.append(score)
            
            # 作业成绩 (8次)
            homeworks = []
            print("请输入8次作业成绩:")
            for i in range(1, 9):
                score = float(input(f"作业{i}: "))
                homeworks.append(score)
            
            # 在线学习部分
            online_learning_70 = float(input("请输入在线学习(70%部分)成绩: "))
            online_learning_20 = float(input("请输入在线学习(20%部分)成绩: "))
            online_learning_10 = float(input("请输入在线学习(10%部分)成绩: "))
            
            # 平时总合和期末成绩
            usual_total = float(input("请输入平时总合成绩: "))
            final_exam = float(input("请输入期末成绩: "))
            total_score = float(input("请输入总评成绩: "))
            
            # 创建学生字典
            student = {
                'student_id': student_id,
                'name': name,
                'class': class_name,
                'experiments': experiments,
                'homeworks': homeworks,
                'online_learning_70': online_learning_70,
                'online_learning_20': online_learning_20,
                'online_learning_10': online_learning_10,
                'usual_total': usual_total,
                'final_exam': final_exam,
                'total_score': total_score
            }
            
            students.append(student)
            print(f"成功添加学生: {name} (学号: {student_id})")
            
            another = input("是否继续添加？(y/n): ").strip().lower()
            if another != 'y':
                break
                
        except ValueError:
            print("输入错误！成绩必须是数字，请重新输入。")
        except KeyboardInterrupt:
            print("\n操作已取消")
            break

def show_all():
    """显示所有学生信息"""
    print("\n--- 所有学生信息 ---")
    if not students:
        print("暂无学生信息！")
        return
        
    # 打印表头
    header = f"{'序号':<4} {'学号':<12} {'姓名':<8} {'班级':<6} "
    # 实验成绩
    for i in range(1, 9):
        header += f"{'实验'+str(i):<6}"
    # 作业成绩
    for i in range(1, 9):
        header += f"{'作业'+str(i):<6}"
    # 在线学习和总成绩
    header += f"{'在线70%':<8} {'在线20%':<8} {'在线10%':<8} {'平时总合':<8} {'期末':<6} {'总评':<6}"
    
    print(header)
    print("-" * 150)
    
    # 打印每个学生的信息
    for i, student in enumerate(students, 1):
        row = f"{i:<4} {student['student_id']:<12} {student['name']:<8} {student['class']:<6} "
        
        # 实验成绩
        for exp in student['experiments']:
            row += f"{exp:<6.0f}"
        
        # 作业成绩
        for hw in student['homeworks']:
            row += f"{hw:<6.0f}"
        
        # 在线学习和总成绩
        row += f"{student['online_learning_70']:<8.0f} {student['online_learning_20']:<8.0f} "
        row += f"{student['online_learning_10']:<8.0f} {student['usual_total']:<8.0f} "
        row += f"{student['final_exam']:<6.0f} {student['total_score']:<6.0f}"
        
        print(row)

def search_stu():
    """搜索学生信息"""
    print("\n--- 搜索学生信息 ---")
    if not students:
        print("暂无学生信息！")
        return
        
    keyword = input("请输入要搜索的学生学号或姓名: ").strip()
    found = [s for s in students if keyword in s['student_id'] or keyword in s['name']]
    
    if not found:
        print(f"未找到相关学生！")
        return
        
    # 打印表头
    header = f"{'学号':<12} {'姓名':<8} {'班级':<6} "
    # 实验成绩
    for i in range(1, 9):
        header += f"{'实验'+str(i):<6}"
    # 作业成绩
    for i in range(1, 9):
        header += f"{'作业'+str(i):<6}"
    # 在线学习和总成绩
    header += f"{'在线70%':<8} {'在线20%':<8} {'在线10%':<8} {'平时总合':<8} {'期末':<6} {'总评':<6}"
    
    print(header)
    print("-" * 150)
    
    for student in found:
        row = f"{student['student_id']:<12} {student['name']:<8} {student['class']:<6} "
        
        # 实验成绩
        for exp in student['experiments']:
            row += f"{exp:<6.0f}"
        
        # 作业成绩
        for hw in student['homeworks']:
            row += f"{hw:<6.0f}"
        
        # 在线学习和总成绩
        row += f"{student['online_learning_70']:<8.0f} {student['online_learning_20']:<8.0f} "
        row += f"{student['online_learning_10']:<8.0f} {student['usual_total']:<8.0f} "
        row += f"{student['final_exam']:<6.0f} {student['total_score']:<6.0f}"
        
        print(row)

def delete_stu():
    """删除学生信息"""
    print("\n--- 删除学生信息 ---")
    if not students:
        print("暂无学生信息！")
        return
        
    show_all()
    try:
        index = int(input("请输入要删除的学生序号: ")) - 1
        if 0 <= index < len(students):
            deleted = students.pop(index)
            print(f"已删除学生: {deleted['name']} (学号: {deleted['student_id']})")
        else:
            print("无效的序号！")
    except ValueError:
        print("请输入有效的数字！")

def calculate_statistics():
    """计算成绩统计"""
    print("\n--- 成绩统计 ---")
    if not students:
        print("暂无学生信息！")
        return
    
    # 计算实验平均分
    exp_avgs = []
    for i in range(8):
        total = sum(student['experiments'][i] for student in students)
        exp_avgs.append(total / len(students))
    
    # 计算作业平均分
    hw_avgs = []
    for i in range(8):
        total = sum(student['homeworks'][i] for student in students)
        hw_avgs.append(total / len(students))
    
    # 计算其他项目的平均分
    online_70_avg = sum(student['online_learning_70'] for student in students) / len(students)
    online_20_avg = sum(student['online_learning_20'] for student in students) / len(students)
    online_10_avg = sum(student['online_learning_10'] for student in students) / len(students)
    usual_avg = sum(student['usual_total'] for student in students) / len(students)
    final_avg = sum(student['final_exam'] for student in students) / len(students)
    total_avg = sum(student['total_score'] for student in students) / len(students)
    
    # 打印实验平均分
    print("实验平均分:")
    for i, avg in enumerate(exp_avgs, 1):
        print(f"实验{i}: {avg:.2f}")
    
    # 打印作业平均分
    print("\n作业平均分:")
    for i, avg in enumerate(hw_avgs, 1):
        print(f"作业{i}: {avg:.2f}")
    
    # 打印其他平均分
    print(f"\n在线学习(70%)平均分: {online_70_avg:.2f}")
    print(f"在线学习(20%)平均分: {online_20_avg:.2f}")
    print(f"在线学习(10%)平均分: {online_10_avg:.2f}")
    print(f"平时总合平均分: {usual_avg:.2f}")
    print(f"期末平均分: {final_avg:.2f}")
    print(f"总评平均分: {total_avg:.2f}")

def save_to_file():
    """保存数据到文件"""
    try:
        with open("students.txt", "w", encoding="utf-8") as f:
            # 写入表头
            header = "学号,姓名,班级,"
            header += ",".join([f"实验{i}" for i in range(1, 9)])
            header += ","
            header += ",".join([f"作业{i}" for i in range(1, 9)])
            header += ",在线70%,在线20%,在线10%,平时总合,期末,总评\n"
            f.write(header)
            
            # 写入数据
            for student in students:
                line = f"{student['student_id']},{student['name']},{student['class']},"
                line += ",".join([str(exp) for exp in student['experiments']])
                line += ","
                line += ",".join([str(hw) for hw in student['homeworks']])
                line += f",{student['online_learning_70']},{student['online_learning_20']},"
                line += f"{student['online_learning_10']},{student['usual_total']},"
                line += f"{student['final_exam']},{student['total_score']}\n"
                f.write(line)
        print("数据已保存到 students.txt")
    except Exception as e:
        print(f"保存文件时出错: {e}")

def load_from_file():
    """从文件加载数据"""
    global students
    try:
        with open("students.txt", "r", encoding="utf-8") as f:
            lines = f.readlines()
            # 跳过表头
            for line in lines[1:]:
                data = line.strip().split(',')
                if len(data) >= 28:  # 确保有足够的数据项
                    student = {
                        'student_id': data[0],
                        'name': data[1],
                        'class': data[2],
                        'experiments': [float(x) for x in data[3:11]],
                        'homeworks': [float(x) for x in data[11:19]],
                        'online_learning_70': float(data[19]),
                        'online_learning_20': float(data[20]),
                        'online_learning_10': float(data[21]),
                        'usual_total': float(data[22]),
                        'final_exam': float(data[23]),
                        'total_score': float(data[24])
                    }
                    students.append(student)
        print("数据已从 students.txt 加载")
    except FileNotFoundError:
        print("未找到数据文件，将从空列表开始")
    except Exception as e:
        print(f"加载文件时出错: {e}")

def main():
    """主函数"""
    # 启动时加载数据
    load_from_file()
    
    while True:
        print("\n" + "="*50)
        print("          学生成绩管理系统")
        print("="*50)
        print("1. 添加学生")
        print("2. 查看所有学生")
        print("3. 搜索学生")
        print("4. 删除学生")
        print("5. 成绩统计")
        print("6. 保存数据")
        print("7. 退出系统")
        print("="*50)
        
        choice = input("请选择操作 (1-7): ").strip()
        
        if choice == '1':
            add_stu()
        elif choice == '2':
            show_all()
        elif choice == '3':
            search_stu()
        elif choice == '4':
            delete_stu()
        elif choice == '5':
            calculate_statistics()
        elif choice == '6':
            save_to_file()
        elif choice == '7':
            save_to_file()  # 退出前自动保存
            print("感谢使用学生成绩管理系统，再见！")
            break
        else:
            print("无效选择，请重新输入！")

# 程序入口
if __name__ == "__main__":
    main()